package com.example.demo.controller.index;

import com.example.demo.model.ResponseData;
import com.mongodb.client.ListIndexesIterable;
import com.mongodb.client.model.Indexes;
import io.swagger.annotations.ApiOperation;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;


/**
 * @author hanqiang
 * @Classname IndexController
 * @Date 2020/10/4 22:11
 * @Description:
 */
@RestController
@RequestMapping("/index")
public class IndexController {
    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 该方法创建异常索引之后全部删除，再次创建索引就会报 500 的错误，不知为什么
     */
    @ApiOperation(value="创建索引", notes = "创建升序索引")
    @PostMapping("/createIndex")
    public ResponseData createIndex(){
        String collectionName="shops";
        String attributeName="name";
        return ResponseData.success(
                mongoTemplate.createCollection(collectionName).createIndex(Indexes.text(attributeName)));
    }

    @ApiOperation(value="创建索引",notes = "创建降序索引")
    @PostMapping("/createIndexDes")
    public ResponseData createIndexDes(){
        String collectionName="shops";
        String attributeName="price";
        return ResponseData.success(
                mongoTemplate.getCollection(collectionName).createIndex(Indexes.descending(attributeName)));
    }

    @ApiOperation(value="查询索引",notes="查询索引")
    @GetMapping("/queryIndex")
    public ResponseData queryIndex(){
        String collectionName="shops";
        ListIndexesIterable<Document> listIndexesIterable= mongoTemplate.getCollection(collectionName).listIndexes();
        List<Document> indexList=new ArrayList<>();
        for(Document listindex:listIndexesIterable){
            indexList.add(listindex);
        }
        return ResponseData.success(indexList);
    }

    @ApiOperation(value="删除索引",notes="删除索引")
    @PostMapping("/removeIndex")
    public ResponseData removeIndex(){
        String collectionName="shops";
        String attributeName="price_-1";
        mongoTemplate.getCollection(collectionName).dropIndex(attributeName);
        return ResponseData.success();
    }

    @ApiOperation(value="删除全部索引",notes = "删除全部索引")
    @PostMapping("removeAllIndex")
    public ResponseData removeAllIndex(){
        String collectionName="shops";
        mongoTemplate.getCollection(collectionName).dropIndexes();
        return ResponseData.success();
    }
}
